package ldh.im.fxbase.util;

import ldh.im.fxbase.richtext.TextItem;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexUtil {

    private static final String URL_REGEX = "^(?:https?://)[\\w]{1,}(?:\\.?[\\w]{1,})+[\\w-_/?&=#%:]*$";

    public static boolean isUrl(String content) {
        Pattern pattern = Pattern.compile(URL_REGEX);
        return pattern.matcher(content).matches();
    }

    public static boolean isRichText(String content) {
        return content.contains(TextItem.SPLIT_STRING);
    }

    public static List<String> split(String reg, String content) {
        List<String> result = new ArrayList<>();
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(content);
        int preIdx = 0;
        while(matcher.find()) {
            String str = matcher.group(0);
            int idx = matcher.start();
            String preStr = content.substring(preIdx, idx);
            if (!preStr.equals("")) {
                result.add(preStr);
            }
            result.add(str);
            preIdx = matcher.end();
        }
        if (preIdx < content.length()) {
            String str = content.substring(preIdx, content.length());
            if (!str.equals("")) {
                result.add(str);
            }
        }
        return result;
    }
}
